#!/bin/sh
# 20-huawei - Battery Plugin for Huawei MateBooks w/ huawei_wmi driver
#
# Copyright (c) 2025 Thomas Koch <linrunner at gmx.net> and others.
# SPDX-License-Identifier: GPL-2.0-or-later

# Needs: tlp-func-base, 35-tlp-func-batt, tlp-func-stat

# --- Hardware Detection

readonly BATDRV_HUAWEI_MD=/sys/devices/platform/huawei-wmi

batdrv_is_huawei () {
    # check if kernel module loaded
    # rc: 0=Huawei, 1=other hardware
    [ -d $BATDRV_HUAWEI_MD ]
}

# --- Plugin API functions

readonly BATDRV_HUAWEI_THRESH="${BATDRV_HUAWEI_MD}/charge_control_thresholds"


batdrv_init () {
    # detect hardware and initialize driver
    # rc: 0=matching hardware detected/1=not detected/2=no batteries detected
    # retval: $_batdrv_plugin, $_batdrv_kmod
    #
    # 1. check for native kernel acpi (Linux 5.4 or higher required)
    #    --> retval $_natacpi:
    #       0=thresholds/
    #       32=disabled/
    #       128=no kernel support/
    #       254=laptop not supported
    #
    # 2. determine method for
    #    reading battery data                   --> retval $_bm_read,
    #    reading/writing charging thresholds    --> retval $_bm_thresh,
    #    reading/writing force discharge        --> retval $_bm_dischg:
    #       none/natacpi
    #
    # 3. determine present batteries
    #    list of batteries (space separated)    --> retval $_batteries;
    #
    # 4. determine charge threshold config, sysfile and defaults
    #    sysfile (start and stop threshold)     --> retval $_bf_start_stop,
    #    start default                          --> retval $_bt_def_start,
    #    stop default                           --> retval $_bt_def_stop;

    _batdrv_plugin="huawei"
    _batdrv_kmod="huawei_wmi" # kernel module for natacpi

    # check plugin simulation override and denylist
    if [ -n "$X_BAT_PLUGIN_SIMULATE" ]; then
        if [ "$X_BAT_PLUGIN_SIMULATE" = "$_batdrv_plugin" ]; then
            echo_debug "bat" "batdrv_init.${_batdrv_plugin}.simulate"
        else
            echo_debug "bat" "batdrv_init.${_batdrv_plugin}.simulate_skip"
            return 1
        fi
    elif wordinlist "$_batdrv_plugin" "$X_BAT_PLUGIN_DENYLIST"; then
        echo_debug "bat" "batdrv_init.${_batdrv_plugin}.denylist"
        return 1
    else
        # check if hardware matches
        if ! batdrv_is_huawei; then
            echo_debug "bat" "batdrv_init.${_batdrv_plugin}.no_match"
            return 1
        fi
    fi

    # presume no features at all
    _natacpi=128
    _bm_read="natacpi"
    _bm_thresh="none"
    _bm_dischg="none"
    _batteries=""
    _bt_def_start=0
    _bt_def_stop=100

    # iterate batteries
    local bd bs
    for bd in "$ACPIBATDIR"/BAT[01]; do
        if [ "$(read_sysf "$bd/present")" = "1" ]; then
            # record detected batteries and directories
            bs=${bd##/*/}
            if [ -n "$_batteries" ]; then
                _batteries="$_batteries $bs"
            else
                _batteries="$bs"
            fi
        fi
    done

    # check for vendor specific kernel api
    if [ "$NATACPI_ENABLE" = "0" ]; then
        # natacpi disabled in configuration --> skip actual detection
        _natacpi=32
    elif [ -f "$BATDRV_HUAWEI_THRESH" ] && readable_sysf "$BATDRV_HUAWEI_THRESH"; then
        # sysfile exists and is actually readable
        _natacpi=0
        _bm_thresh="natacpi"
        _bf_start_stop="$BATDRV_HUAWEI_THRESH"
    elif [ "$X_BAT_PLUGIN_SIMULATE" = "$_batdrv_plugin" ]; then
        # simulate api
        _natacpi=0
        _bm_thresh="natacpi"
        _bf_start_stop="$BATDRV_HUAWEI_THRESH"
    else
        # nothing detected
        _natacpi=254
    fi

    # shellcheck disable=SC2034
    _batdrv_selected=$_batdrv_plugin
    echo_debug "bat" "batdrv_init.${_batdrv_plugin}: batteries=$_batteries; natacpi=$_natacpi; thresh=$_bm_thresh; start_stop=$_bf_start_stop;"
    return 0
}

batdrv_select_battery () {
    # determine battery acpidir
    # $1: BAT0/BAT1/DEF
    # global params: $_batdrv_plugin, $_batteries
    # rc: 0=bat exists/1=bat non-existent
    # retval: $_bat_str:    BAT0/BAT1;
    #         $_bt_cfg_bat: config suffix (BAT0/BAT1);
    #         $_bd_read:    directory with battery data sysfiles;
    # prerequisite: batdrv_init()

    # defaults
    _bat_str=""   # no bat
    _bd_read=""   # no directory

    local bat="$1"

    # convert battery param to uppercase
    bat="$(printf '%s' "$bat" | tr "[:lower:]" "[:upper:]")"

    # validate battery param
    case "$bat" in
        DEF) # 1st battery is default
            _bat_str="${_batteries%% *}"
            ;;

        *)
            if wordinlist "$bat" "$_batteries"; then
                _bat_str="$bat"
            else
                # battery not present --> quit
                echo_debug "bat" "batdrv.${_batdrv_plugin}.select_battery($1).not_present"
                return 1
            fi
            ;;
    esac

    # all batteries share the BAT0 config parameters
    _bt_cfg_bat="BAT0"

    # determine natacpi sysfiles
    _bd_read="$ACPIBATDIR/$_bat_str"

    echo_debug "bat" "batdrv.${_batdrv_plugin}.select_battery($1): bat_str=$_bat_str; cfg=$_bt_cfg_bat; bd_read=$_bd_read;"
    return 0
}

batdrv_read_threshold () {
    # read and print both charge thresholds
    # $1: start/stop - unused dummy for plugin api compatibility
    # $2: 0=api/1=tlp-stat output - unused dummy for plugin api compatibility
    # global params: $_batdrv_plugin, $_bm_thresh, $_bf_start_stop
    # out: both thresholds 0..100 separated with a blank/"" on error
    # rc: 0=ok/4=read error/255=no api
    # prerequisite: batdrv_init(), batdrv_select_battery()

    local rc=0
    local out="$X_THRESH_SIMULATE_START $X_THRESH_SIMULATE_STOP"

    if [ "$out" != " " ]; then
        printf "%s" "$out"
        echo_debug "bat" "batdrv.${_batdrv_plugin}.read_threshold.simulate: bm_thresh=$_bm_thresh; out=$out; rc=$rc"
        return 0
    fi

    if [ "$_bm_thresh" = "natacpi" ]; then
        out=$(read_sysf "$_bf_start_stop") || rc=4
    else
        rc=255
    fi

    # "return" threshold
    if [ "$X_THRESH_SIMULATE_READERR" != "1" ]; then
        printf "%s" "$out"
    else
        rc=4
    fi

    echo_debug "bat" "batdrv.${_batdrv_plugin}.read_threshold: bm_thresh=$_bm_thresh; bf_start_stop=$_bf_start_stop; out=$out; rc=$rc"
    return $rc
}

batdrv_write_thresholds () {
    # write both charge thresholds for a battery
    # use pre-determined method and sysfiles from global parms
    # $1: new start threshold 0(off)..100/DEF(default)
    # $2: new stop threshold 0(off)..100(off)/DEF(default)
    # $3: 0=quiet/1=output parameter errors/2=output progress and errors
    # $4: non-empty string indicates thresholds stem from configuration
    # global params: $_batdrv_plugin, $_bm_thresh, $_bt_cfg_bat, $_bf_start_stop
    # rc: 0=ok/
    #     1=not configured/
    #     2=threshold(s) out of range or non-numeric/
    #     3=minimum start stop diff violated/
    #     5=threshold write error
    # prerequisite: batdrv_init(), batdrv_select_battery()
    local new_start=${1:-}
    local new_stop=${2:-}
    local verb=${3:-0}

    # insert defaults
    [ "$new_start" = "DEF" ] && new_start=$_bt_def_start
    [ "$new_stop" = "DEF" ] && new_stop=$_bt_def_stop

    # --- validate thresholds
    if [ -n "$4" ] && [ -z "$new_start" ] && [ -z "$new_stop" ]; then
        # do nothing if unconfigured
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($1, $2, $3, $4).not_configured: cfg=$_bt_cfg_bat"
        return 1
    fi

    # start: check for 3 digits max, ensure min 0 / max 99
    if ! is_uint "$new_start" 3 || \
       ! is_within_bounds "$new_start" 0 99; then
        # threshold out of range
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($1, $2, $3, $4).invalid_start: cfg=$_bt_cfg_bat"
        case $verb in
            1)
                if [ -n "$4" ]; then
                    echo_message "Error in configuration at START_CHARGE_THRESH_${_bt_cfg_bat}=\"${new_start}\": not specified, invalid or out of range (0..99). Skipped."
                fi
                ;;

            2)
                if [ -n "$4" ]; then
                    cprintf "" "Error in configuration at START_CHARGE_THRESH_%s=\"%s\": not specified, invalid or out of range (0..99). Aborted.\n" "$_bt_cfg_bat" "$new_start" 1>&2
                else
                    cprintf "" "Error: start charge threshold (%s) is not specified, invalid or out of range (0..99). Aborted.\n" "$new_start" 1>&2
                fi
                ;;
        esac
        return 2
    fi

    # stop: check for 3 digits max, ensure min 1 / max 100
    if ! is_uint "$new_stop" 3 || \
       ! is_within_bounds "$new_stop" 1 100; then
        # threshold out of range
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($1, $2, $3, $4).invalid_stop: cfg=$_bt_cfg_bat"
        case $verb in
            1)
                if [ -n "$4" ]; then
                    echo_message "Error in configuration at STOP_CHARGE_THRESH_${_bt_cfg_bat}=\"${new_stop}\": not specified, invalid or out of range (1..100). Skipped."
                fi
                ;;

            2)
                if [ -n "$4" ]; then
                    cprintf "" "Error in configuration at STOP_CHARGE_THRESH_%s=\"%s\": not specified, invalid or out of range (1..100). Aborted.\n" "$_bt_cfg_bat" "$new_stop" 1>&2
                else
                    cprintf "" "Error: stop charge threshold (%s) is not specified, invalid or out of range (1..100). Aborted.\n" "$new_stop" 1>&2
                fi
                ;;
        esac
        return 2
    fi

    # check start <= stop
    if [ "$new_start" -gt "$new_stop" ]; then
        echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($1, $2, $3, $4).invalid_diff: cfg=$_bt_cfg_bat"
        case $verb in
            1)
                if [ -n "$4" ]; then
                    echo_message "Error in configuration: START_CHARGE_THRESH_${_bt_cfg_bat} > STOP_CHARGE_THRESH_${_bt_cfg_bat}. Skipped."
                fi
                ;;

            2)
                if [ -n "$4" ]; then
                    cprintf "" "Error in configuration: START_CHARGE_THRESH_%s > STOP_CHARGE_THRESH_%s. Aborted.\n" "$_bt_cfg_bat" "$_bt_cfg_bat" 1>&2
                else
                    cprintf "" "Error: start threshold > stop threshold. Aborted.\n" 1>&2
                fi
                ;;
        esac
        return 3
    fi

    # write new thresholds
    if [ "$verb" = "2" ]; then
        printf "Setting temporary charge thresholds:\n" 1>&2
    fi

    local rc=0
    local new_threshs="$new_start $new_stop"
    write_sysf "$new_threshs" "$_bf_start_stop" || rc=5
    echo_debug "bat" "batdrv.${_batdrv_plugin}.write_thresholds($1, $2, $3, $4): cfg=$_bt_cfg_bat; new=$new_threshs; rc=$rc"
    case $verb in
        2)
            if [ $rc -eq 0 ]; then
                printf "  %s = %d, %s = %d\n" start "$new_start" stop "$new_stop" 1>&2
            else
                cprintf "err" "  %s = %d, %s = %d (Error: write failed)\n" start "$new_start" stop "$new_stop" 1>&2
            fi
            ;;
        1)
            if [ $rc -gt 0 ]; then
                echo_message "Error: writing charge thresholds failed."
            fi
            ;;
    esac

    if [ "$rc" -eq 0 ] && [ "$verb" = "2" ]; then
        soc_gt_stop_notice
    fi

    return $rc
}

# shellcheck disable=SC2120
batdrv_calc_soc () {
    # calc and print battery charge level (rounded)
    # $1: format (optional)
    # global param: $_bd_read
    # prerequisite: batdrv_init(), batdrv_select_battery()
    # rc: 0=ok/1=charge level read error
    local ef en

    if [ -f "$_bd_read/energy_full" ]; then
        ef=$(read_sysval "$_bd_read/energy_full")
        en=$(read_sysval "$_bd_read/energy_now")
    elif [ -f "$_bd_read/charge_full" ]; then
        ef=$(read_sysval "$_bd_read/charge_full")
        en=$(read_sysval "$_bd_read/charge_now")
    else
        ef=0
        en=0
    fi

    if [ "$ef" != "0" ]; then
        if [ -n "$1" ]; then
            perl -e 'printf ("'"$1"'", 100.0 * '"$en"' / '"$ef"')'
        else
            perl -e 'printf ("%d", int(100.0 * '"$en"' / '"$ef"' + 0.5))'
        fi
        return 0
    else
        printf "255"
        return 1
    fi
}

batdrv_chargeonce () {
    # function not implemented for Huawei MateBooks
    # global param: $_batdrv_plugin
    # prerequisite: batdrv_init()

    echo_debug "bat" "batdrv.${_batdrv_plugin}.charge_once.not_implemented"
    return 255
}

batdrv_apply_configured_thresholds () {
    # apply configured stop thresholds from configuration to all batteries
    # - called for bg tasks tlp init [re]start/auto and tlp start
    # output parameter errors only
    # prerequisite: batdrv_init()

    local start_thresh stop_thresh

    if batdrv_select_battery "DEF"; then
        eval start_thresh="\$START_CHARGE_THRESH_${_bt_cfg_bat}"
        eval stop_thresh="\$STOP_CHARGE_THRESH_${_bt_cfg_bat}"
        batdrv_write_thresholds "$start_thresh" "$stop_thresh" 1 1
    fi

    return 0
}

batdrv_read_force_discharge () {
    # function not implemented for Huawei MateBooks
    # global param: $_batdrv_plugin
    # prerequisite: batdrv_init()

    echo_debug "bat" "batdrv.${_batdrv_plugin}.read_force_discharge.not_implemented"
    return 255
}

batdrv_write_force_discharge () {
    # function not implemented for Huawei MateBooks
    # global param: $_batdrv_plugin
    # prerequisite: batdrv_init()

    echo_debug "bat" "batdrv.${_batdrv_plugin}.write_force_discharge.not_implemented"
    return 255
}

batdrv_cancel_force_discharge () {
    # function not implemented for Huawei MateBooks
    # global param: $_batdrv_plugin
    # prerequisite: batdrv_init()

    echo_debug "bat" "batdrv.${_batdrv_plugin}.cancel_force_discharge.not_implemented"
    return 255
}

batdrv_force_discharge_active () {
    # function not implemented for Huawei MateBooks
    # global param: $_batdrv_plugin
    # prerequisite: batdrv_init()

    echo_debug "bat" "batdrv.${_batdrv_plugin}.force_discharge_active.not_implemented"
    return 255
}

batdrv_discharge_safetylock () {
    # check safety lock - force-discharge not implemented for Huawei MateBooks
    # $1: discharge/recalibrate
    # rc: 0=engaged/1=disengaged

    return 1
}

batdrv_discharge () {
    # function not implemented for Huawei MateBooks
    # global param: $_batdrv_plugin
    # prerequisite: batdrv_init()

    # Important: release lock from caller
    unlock_tlp tlp_discharge

    echo_debug "bat" "batdrv.${_batdrv_plugin}.discharge.not_implemented"
    return 255
}

batdrv_show_battery_data () {
    # output battery status
    # $1: 1=verbose
    # global params: $_batdrv_plugin, $_batteries, $_batdrv_kmod, $_natacpi, $_bd_read, $_bf_start_stop
    # prerequisite: batdrv_init()
    local verbose=${1:-0}
    local threshs

    printf "+++ Battery Care\n"
    printf "Plugin: %s\n" "$_batdrv_plugin"

    if [ "$_bm_thresh" = "natacpi" ]; then
        cprintf "success" "Supported features: charge thresholds\n"
    else
        cprintf "warning" "Supported features: none available\n"
    fi

    printf "Driver usage:\n"
    # native kernel ACPI battery API
    case $_natacpi in
        0)   cprintf "success" "* vendor (%s) = active (charge thresholds)\n" "$_batdrv_kmod" ;;
        32)  cprintf "notice"  "* vendor (%s) = inactive (disabled by configuration)\n" "$_batdrv_kmod" ;;
        128) cprintf "err"     "* vendor (%s) = inactive (no kernel support)\n" "$_batdrv_kmod" ;;
        254) cprintf "warning" "* vendor (%s) = inactive (laptop not supported)\n" "$_batdrv_kmod" ;;
        *)   cprintf "err"     "* vendor (%s) = unknown status\n" "$_batdrv_kmod" ;;
    esac

    if [ "$_bm_thresh" = "natacpi" ]; then
        printf "Parameter value ranges:\n"
        printf "* START_CHARGE_THRESH_BAT0:  0(default)..99\n"
        printf "* STOP_CHARGE_THRESH_BAT0:   1..100(default)\n\n"
        if threshs=$(batdrv_read_threshold); then
            case "$threshs" in
                "0 0"|"0 100")
                    printf "%-59s = %s [%%] (disabled)\n" "$_bf_start_stop" "$threshs"
                    ;;

                *)  printf "%-59s = %s [%%]\n"       "$_bf_start_stop" "$threshs"
                    ;;
            esac
        else
            printf "%-59s = %s\n" "$_bf_start_stop" "(not available)"
        fi
    fi
    printf "\n"

    # -- show battery data
    local bat
    local bcnt=0
    local ed ef en
    local efsum=0
    local ensum=0

    for bat in $_batteries; do # iterate batteries
        batdrv_select_battery "$bat"

        printf "+++ Battery Status: %s\n" "$bat"

        printparm "%-59s = ##%s##" "$_bd_read/manufacturer"
        printparm "%-59s = ##%s##" "$_bd_read/model_name"

        print_battery_cycle_count "$_bd_read/cycle_count" "$(read_sysf "$_bd_read/cycle_count")"

        if [ -f "$_bd_read/energy_full" ]; then
            printparm "%-59s = ##%6d## [mWh]" "$_bd_read/energy_full_design" "" 000
            printparm "%-59s = ##%6d## [mWh]" "$_bd_read/energy_full" "" 000
            printparm "%-59s = ##%6d## [mWh]" "$_bd_read/energy_now" "" 000
            printparm "%-59s = ##%6d## [mW]" "$_bd_read/power_now" "" 000

            # store values for charge / capacity calculation below
            ed=$(read_sysval "$_bd_read/energy_full_design")
            ef=$(read_sysval "$_bd_read/energy_full")
            en=$(read_sysval "$_bd_read/energy_now")
            efsum=$((efsum + ef))
            ensum=$((ensum + en))

        elif [ -f "$_bd_read/charge_full" ]; then
            printparm "%-59s = ##%6d## [mAh]" "$_bd_read/charge_full_design" "" 000
            printparm "%-59s = ##%6d## [mAh]" "$_bd_read/charge_full" "" 000
            printparm "%-59s = ##%6d## [mAh]" "$_bd_read/charge_now" "" 000
            printparm "%-59s = ##%6d## [mA]" "$_bd_read/current_now" "" 000

            # store values for charge / capacity calculation below
            ed=$(read_sysval "$_bd_read/charge_full_design")
            ef=$(read_sysval "$_bd_read/charge_full")
            en=$(read_sysval "$_bd_read/charge_now")
            efsum=$((efsum + ef))
            ensum=$((ensum + en))

        else
            ed=0
            ef=0
            en=0
        fi

        print_batstate "$_bd_read/status"
        printf "\n"

        if [ "$verbose" -eq 1 ]; then
            printparm "%-59s = ##%6s## [mV]" "$_bd_read/voltage_min_design" "" 000
            printparm "%-59s = ##%6s## [mV]" "$_bd_read/voltage_now" "" 000
            printf "\n"
        fi

        # --- show charge level (SOC) and capacity
        lf=0
        if [ "$ef" -ne 0 ]; then
            perl -e 'printf ("%-59s = %6.1f [%%]\n", "Charge",   100.0 * '"$en"' / '"$ef"');'
            lf=1
        fi
        if [ "$ed" -ne 0 ]; then
            perl -e 'printf ("%-59s = %6.1f [%%]\n", "Capacity", 100.0 * '"$ef"' / '"$ed"');'
            lf=1
        fi
        [ "$lf" -gt 0 ] && printf "\n"

        bcnt=$((bcnt+1))

    done # for bat

    if [ $bcnt -gt 1 ] && [ $efsum -ne 0 ]; then
        # more than one battery detected --> show charge total
        perl -e 'printf ("%-59s = %6.1f [%%]\n", "+++ Charge total",   100.0 * '"$ensum"' / '"$efsum"');'
        printf "\n"
    fi

    return 0
}

batdrv_check_soc_gt_stop () {
    # check if battery charge level (SOC) is greater than the stop threshold
    # rc: 0=greater/1=less or equal (or thresholds not supported)
    # global params: $_bm_thresh, $_bat_str
    # prerequisite: batdrv_init(), batdrv_select_battery()
    local soc stop

    if [ "$_bm_thresh" = "natacpi" ] && soc="$(batdrv_calc_soc)"; then
        stop="$(batdrv_read_threshold | awk '{print $2; }')"
        if is_uint "$stop" 3 && [ "$soc" -gt "$stop" ]; then
            return 0
        fi
    fi

    return 1
}

batdrv_recommendations () {
    # output Huawei MateBook specific recommendations
    # prerequisite: batdrv_init()

    soc_gt_stop_recommendation

    return 0
}
